package cn.yanhu.kuwanapp.my.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Message
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import app.dinus.com.itemdecoration.GridOffsetsItemDecoration
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.adapter.OnItemClickListener
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.SystemAppUtil
import cn.woochen.comlib.util.ext.dp
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.bean.other.WithdrawMethodBean
import cn.yanhu.kuwanapp.bean.response.RespWithdrawHomeBean
import cn.yanhu.kuwanapp.databinding.ActivityWithdrawBinding
import cn.yanhu.kuwanapp.event.AccountAuthEvent
import cn.yanhu.kuwanapp.http.status.ErrorCode
import cn.yanhu.kuwanapp.my.adapter.WithdrawMethodAdapter
import cn.yanhu.kuwanapp.my.adapter.WithdrawOptionAdapter
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.AlipayUtil
import cn.yanhu.kuwanapp.utils.AuthResult
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.ext.parseState2
import cn.yanhu.kuwanapp.utils.ext.showToast
import cn.yanhu.kuwanapp.utils.third.AccountReqType
import cn.yanhu.kuwanapp.utils.third.AccountType
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import cn.yanhu.kuwanapp.widgets.recycler.RecycleViewDivider
import com.alipay.sdk.app.AuthTask
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlin.concurrent.thread

/**
 * 类描述：提现
 * @author：woochen
 * create at：2021/8/4 6:26 AM
 */
class WithdrawActivity : BaseActivity<ActivityWithdrawBinding, UserViewModel>(),
    OnSingleClickListener {

    private val mWithdrawOptionDatas by lazy {
        mutableListOf<RespWithdrawHomeBean.RewardOptional>()
    }

    private val mWithdrawOptionAdapter by lazy {
        WithdrawOptionAdapter(mWithdrawOptionDatas)
    }

    private val mWithdrawMethodDatas by lazy {
        mutableListOf<WithdrawMethodBean>(
            WithdrawMethodBean(1, "支付宝", R.drawable.ic_alipay, true, true, false, ""),
            WithdrawMethodBean(2, "微信零钱", R.drawable.ic_wxpay, false, false, true, "")
        )
    }

    private val mWithdrawMethodAdapter by lazy {
        WithdrawMethodAdapter(mWithdrawMethodDatas)
    }

    override fun setContentView(): Int = R.layout.activity_withdraw

    override fun initData() {
        setStatusBarStyle(false)
        initWidgets()
    }

    override fun initListener() {
        mBinding.tvWithdraw.setOnSingleClickListener(this)
        mBinding.tvCoinDetail.setOnSingleClickListener(this)
    }

    private var currentPosition = 0

    private fun initWidgets() {
        //提现额度
        mBinding.rvOption.run {
            adapter = mWithdrawOptionAdapter
            val offsetsItemDecoration = GridOffsetsItemDecoration(
                GridOffsetsItemDecoration.GRID_OFFSETS_VERTICAL
            )
            offsetsItemDecoration.setHorizontalItemOffsets(11f.dp.toInt())
            addItemDecoration(offsetsItemDecoration)
            mWithdrawOptionAdapter.mItemClickListener = OnItemClickListener { it ->
                val rewardOptional = mWithdrawOptionDatas[it]
                mWithdrawOptionDatas.forEach { it.select = false }
                rewardOptional.select = true
                currentPosition = it
                mWithdrawOptionAdapter.notifyDataSetChanged()
            }
        }
        //提现方式
        mBinding.rvWithdrawType.run {
            adapter = mWithdrawMethodAdapter

            addItemDecoration(
                RecycleViewDivider(
                    mContext, LinearLayoutManager.VERTICAL, 1, Color.parseColor("#F4F4F4")
                )
            )
            mWithdrawMethodAdapter.mItemClickListener = OnItemClickListener {
                val withdrawMethodBean = mWithdrawMethodDatas[it]
                mWithdrawMethodDatas.forEach { it.select = false }
                currentMethodPosition = it
                withdrawMethodBean.select = true
                mWithdrawMethodAdapter.notifyDataSetChanged()
            }
            mWithdrawMethodAdapter.mOperateListener =
                object : WithdrawMethodAdapter.OperateListener {
                    override fun bindPayMethod(position: Int) {
                        val withdrawMethodBean = mWithdrawMethodDatas[position]
                        when (withdrawMethodBean.type) {
                            1 -> { //绑定支付宝
                                bindAlipay()
                            }
                            2 -> { //绑定微信
                                ThirdAccountHelper.sendAuthReq(AccountType.WX, AccountReqType.Auth)
                            }
                        }
                    }
                }
        }
    }

    /**
     * 绑定支付宝
     */
    private fun bindAlipay() {
        if (!SystemAppUtil.isAliPayInstalled(mContext)) {
            showToast("请先安装支付宝")
            return
        }
        mViewModel.bindAlipay()
    }

    private var currentMethodPosition = 0 //当前支付方式索引

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //提现主页
        mViewModel.withdrawHomeInfo.observe(this, Observer { it ->
            parseState(it, {
                updateUI(it)
            })
        })
        //提现
        mViewModel.withdrawInfo.observe(this, Observer { it ->
            parseState2(it, {
                showToast("恭喜您，提现成功!")
                requestData()
            })
        })
        //微信授权码获取成功
        LiveEventBus.get(AccountAuthEvent::class.java).observe(this, Observer {
            val wxCode = it.code ?: ""
            mViewModel.wxAuth(wxCode, "2")
        })
        //微信授权成功
        mViewModel.wxAuthInfo.observe(this, Observer { it ->
            parseState(it, {
                requestData()
            })
        })
        //绑定支付宝
        mViewModel.bindAlipayInfo.observe(this, Observer { it ->
            parseState(it, { data ->
                val map = AlipayUtil.buildAuthInfoMap(data) ?: hashMapOf()
                val param: String? = AlipayUtil.buildOrderParam(map)
                logcom("$param")
                thread {
                    // 构造AuthTask 对象
                    val authTask = AuthTask(mContext)
                    // 调用授权接口，获取授权结果
                    val result: Map<String, String> = authTask.authV2(param, true)
                    runOnUiThread {
                        alipayAuthResult = AuthResult(result, true)
                        alipayBindStatus = alipayAuthResult?.resultStatus ?: ""
                        logcom("alipayAuthResult:${alipayAuthResult} alipayBindStatus:${alipayBindStatus} resultCode:${alipayAuthResult?.resultCode}")
                        val result: String = alipayAuthResult?.result ?: ""
                        mViewModel.bindAlipayCallBack(result)
                    }
                }
            })
        })
        //支付宝绑定回调
        mViewModel.bindAlipayCallBackInfo.observe(this, Observer { it ->
            parseState2(it, {
                // 判断resultStatus 为“9000”且result_code
                // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                if (TextUtils.equals(alipayBindStatus, "9000") && TextUtils.equals(alipayAuthResult?.resultCode, "200")
                ) {
                    // 获取alipay_open_id，调支付时作为参数extern_token 的value
                    // 传入，则支付账户为该授权账户
                    // showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                    showToast("授权成功")
                    requestData()
                } else {
                    // 其他状态值则为授权失败
                    showToast("授权失败")
                }
            })
        })
    }

    private var alipayBindStatus = ""
    private var alipayAuthResult: AuthResult? = null

    /**
     * 提现主页
     */
    private fun updateUI(withdrawInfo: RespWithdrawHomeBean) {
        mBinding.withdrawBean = withdrawInfo
        //提现额度
        mWithdrawOptionDatas.clear()
        mWithdrawOptionDatas.addAll(withdrawInfo.rewardOptionalList)
        if (!mWithdrawOptionDatas.isNullOrEmpty()) mWithdrawOptionDatas[0].select = true
        mWithdrawOptionAdapter.notifyDataSetChanged()
        //提现方式
        mWithdrawMethodDatas[0].run { //支付宝
            select = true
            isBind = withdrawInfo.alipayNickName.isNotBlank()
            payNickname = withdrawInfo.alipayNickName
        }
        mWithdrawMethodDatas[1].run { //微信
            select = false
            isBind = withdrawInfo.weixinNickName.isNotBlank()
            payNickname = withdrawInfo.weixinNickName
        }
        mWithdrawMethodAdapter.notifyDataSetChanged()

    }

    companion object {

        fun start(context: Context) {
            val intent = Intent(context, WithdrawActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onStart() {
        super.onStart()
        requestData()
    }

    override fun requestData() {
        mViewModel.withdrawHome()
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.tvWithdraw -> { //提现
                val goldNum = mBinding.withdrawBean?.goldNum?.toLongOrNull() ?: 0L
                val withdrawOptionBean = mWithdrawOptionDatas[currentPosition]
                val withdrawMethodBean = mWithdrawMethodDatas[currentMethodPosition]
                if (goldNum < withdrawOptionBean.goldNum.toLong()) {
                    showToast("您的金币不足！")
                    return
                }
                if (!withdrawMethodBean.isBind) {
                    showToast("请先绑定${withdrawMethodBean.typeName}!")
                    return
                }
                mViewModel.withdraw(withdrawOptionBean.amount, withdrawMethodBean.type.toString())
            }
            mBinding.tvCoinDetail -> { //金币明细
                WithdrawRecordActivity.start(mContext)
            }
        }
    }
}